import { App } from "vue";
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import * as http from "@/request/http";
import { useUserStore } from "@/store/module/user";
import { ElMessage } from "element-plus";

const routes: RouteRecordRaw[] = [
  // {
  //   path: "/",
  //   redirect: "/login",
  // },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/index.vue"),
  },
  // {
  //   path: "/",
  //   name: "home",
  //   component: () => import("../views/home/index.vue"),
  //   children: [
  //     {
  //       path: "index",
  //       name: "index",
  //       component: () => import("../views/index/index.vue"),
  //     },
  //   ],
  // },

  // {
  //   path: "/ums",
  //   name: "ums",
  //   component: () => import("../views/home/index.vue"),
  //   children: [
  //     {
  //       path: "admin",
  //       name: "admin",
  //       component: () => import("../views/ums/admin.vue"),
  //     },
  //     {
  //       path: "resource",
  //       name: "resource",
  //       component: () => import("../views/ums/resource.vue"),
  //     },
  //   ],
  // },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  // console.log(to, from);
  // 当前有token ，仓库中没有数据
  let token = localStorage.getItem("token");
  const userStore = useUserStore();
  if (token && userStore.menus.length === 0) {
    // 重新请求menu数据
    const adminDate = await http.admin.adminInfo();
    if (adminDate.code == 200) {
      userStore.updateMenus(adminDate.data.menus);
      // 将请求的username辅给pina的username
      userStore.username = adminDate.data.username;
      /////////根据权限数据动态添加路由。
      const menusRouter = userStore.getMenusRouter; //pina的get方法

      // console.log(menusRouter);

      for (let k in menusRouter) {
        // 一级路由
        let routerObj: RouteRecordRaw = {
          path: "/" + menusRouter[k].name,
          name: menusRouter[k].name,
          component: () => import("../views/home/index.vue"),
          children: [],
        };
        // 二级理由
        menusRouter[k].children?.forEach((item) => {
          routerObj.children!.push({
            path: item.name,
            name: item.name,
            component: () =>
              import(`../views/${menusRouter[k].name}/${item.name}.vue`),
          });
        });
        // 添加路由方法
        router.addRoute(routerObj);

        // 添加首页动态路由
        router.addRoute({
          path: "/",
          component: () => import("../views/home/index.vue"),
          children: [
            {
              path: "index",
              name: "index",
              component: () => import("../views/index/index.vue"),
            },
          ],
        });
      }
      //使用了动态路由,需要手动的导航。
      return next(to.fullPath);
    } else {
      //网络有问题
      localStorage.removeItem("token");
      return next("/login");
    }
  } else if (!token && to.path !== "/login") {
    //没有token，也让他跳转到登录页面
    return next("/login");
  } else if (token && to.path === "/login" && userStore.menus.length !== 0) {
    //如果有token，不让他去登录页面，提示他点击退出登录
    ElMessage.warning("请退出登陆！！");
    return next(from.fullPath);
  } else {
    return next();
  }
});

// export default router;
export function initRouter(app: App<Element>) {
  app.use(router);
}

export default router;
